// useEditAdminProduct.ts

import { useMutation, useQueryClient } from "react-query";
import { adminBaseUrl } from "../..";
import { adminProduct } from "../../type";
import { useMemo } from "react";

export const useEditAdminProduct = () => {
  const queryClient = useQueryClient();

  const editProductMutation = useMutation(
    async (data: {
      productId: number;
      updatedProductData: Partial<adminProduct>;
    }) => {
      const { productId, updatedProductData } = data;
      const response = await fetch(`${adminBaseUrl}/${productId}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(updatedProductData),
      });
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.json();
    },
    {
      onSuccess: () => {
        queryClient.invalidateQueries("products"); // Обновляем данные после успешного редактирования товара
      },
    }
  );

  return useMemo(() => editProductMutation, [editProductMutation]);
};
